package com.example.upgradesystem.controller;

import com.example.upgradesystem.model.Package;
import com.example.upgradesystem.repository.PackageRepository;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.util.Date;

@RestController
@RequestMapping("/api/packages")
public class PackageController {
    @Resource
    private PackageRepository packageRepository;

    @PostMapping(consumes = "multipart/form-data")
    public ResponseEntity<?> uploadPackage(@RequestParam("file") MultipartFile file,
                                           @RequestParam("name") String name,
                                           @RequestParam("version") String version) {
        try {
            // 保存文件
            String filePath = saveFile(file);

            // 计算校验和
            String checksum = calculateChecksum(filePath);

            // 创建Package对象
            Package upgradePackage = new Package();
            upgradePackage.setName(name);
            upgradePackage.setVersion(version);
            upgradePackage.setFilePath(filePath);
            upgradePackage.setChecksum(checksum);
            upgradePackage.setUploadDate(new Date());

            // 保存到数据库
            packageRepository.save(upgradePackage);

            return ResponseEntity.ok("Package uploaded successfully.");
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Failed to upload package.");
        }
    }

    private String saveFile(MultipartFile file) throws Exception {
        Path filePath = Paths.get("uploads/" + file.getOriginalFilename());
        Files.createDirectories(filePath.getParent());
        Files.write(filePath, file.getBytes());
        return filePath.toString();
    }

    private String calculateChecksum(String filePath) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
        byte[] hashBytes = digest.digest(fileBytes);

        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}
